package com.doodod.common.utils;

import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.PutPolicy;
import org.json.JSONException;

import java.io.File;

/**
 * 用于进行七牛服务器相关的操作
 * User: 邱孝兵
 * Date: 15-2-5
 * Time: 下午2:52
 */
public class QiNiuUtil {

    // 访问KEY
    public final static String QINIU_ACCESS_KEY = "CaofpFiFcBwNVYgOdpcI91bM-L85qbqaWX_t1XLW";
    // 秘钥
    public final static String QINIU_SECRET_KEY = "maNnrL7uDlwYMqfZlzCw1_wFQ-L6WKvkc_JfjkIP";
    // 空间名
    public final static String QINIU_BUCKET_NAME_DEV = "linglongdev";

    public final static String QINIU_BUCKET_NAME_PROD = "linglongdprod";
    // Http访问地址
    public final static String QINIU_CDN_URL = "";

    /**
     * 上传文件到七牛
     *
     * @param key      文件在七牛服务器上的名称
     * @param filePath 待上传的本地文件的绝对路径
     * @return
     */
    @SuppressWarnings("unused")
    public static boolean uploadFile(String key, String filePath,int devType) {
        try {
            PutExtra putExtra = new PutExtra();
            PutRet ret = IoApi.putFile(getUpToken(devType), key, filePath, putExtra);
            if (null != ret.getKey())
                return true;
        } catch (Exception e) {
            System.out.println(key + "上传到七牛失败");
            return false;
        }
        return false;
    }


    /**
     * 从七牛下载文件到本地
     *
     * @param key      文件在七牛服务器存储的名称
     * @param filePath 保存到本地的文件绝对路径
     * @return
     */
    @SuppressWarnings("unused")
    public static File downloadFile(String key, String filePath) {
        try {
            return HttpUtil.downloadFileFromUrl(filePath, QINIU_CDN_URL + key);
        } catch (Exception e) {
            System.out.println("从七牛下载" + key + "失败");
        }
        return null;
    }

    /**
     * 生成Token
     *
     * @return
     */
    public static String getUpToken(int devType) {
        Mac mac = new Mac(QINIU_ACCESS_KEY, QINIU_SECRET_KEY);
        PutPolicy putPolicy = null;
        if(devType == 0)
            putPolicy = new PutPolicy(QINIU_BUCKET_NAME_DEV);
        else if(devType == 1)
            putPolicy = new PutPolicy(QINIU_BUCKET_NAME_PROD);


        //putPolicy.deadline = 1577811661l;
        try {
            return putPolicy.token(mac);
        } catch (AuthException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

}
